import Layout from "@/layout";
import router from "../router";
import store from "../store";
import Vue from "vue";
import axios from "@/util/axios";


// 动态加载组件
export const loadView = (viewPath) => {
    return () => import(`@/views${viewPath}`);
};

// 标准化路径处理
const normalizePath = (path) => {
    path = path.startsWith("/") ? path : `/${path}`;
    return path.replace(/\/+/g, "/");
};

/**
 * 生成菜单路由
 */
export function generaMenu() {
    // 查询用户菜单
    axios.get("/menus/user/list")
        .then((response) => {
            if (response.data.code === 20000) {
                const routes = response.data.data.map((menu) => {
                    // 处理父级路由
                    const parentRoute = {
                        path: normalizePath(menu.path),
                        component: Layout, // 所有顶级路由都使用Layout包裹
                        meta: { title: menu.name, icon: "iconfont " + menu.icon },
                        redirect: "", // 默认重定向到第一个子路由
                        children: [],
                    };

                    // 处理子路由
                    if (menu.children && menu.children.length > 0) {
                        parentRoute.children = menu.children.map((child) => ({
                            path: normalizePath(child.path),
                            name: child.name,
                            component: loadView(child.component),
                            meta: { icon: "iconfont " + child.icon },
                        }));
                        parentRoute.redirect = parentRoute.children[0].path; // 设置重定向
                    } else {
                        // 无子菜单时将自己作为默认子路由
                        parentRoute.children.push({
                            path: "",
                            name: menu.name,
                            component: loadView(menu.component),
                            meta: { icon: "iconfont " + menu.icon },
                        });
                        parentRoute.redirect = ""; // 访问父路径直接显示子路由
                    }

                    return parentRoute;
                });

                // 提交菜单数据到Vuex
                store.commit("saveUserMenuList", routes);
                // 动态添加路由
                router.addRoutes(routes);
            } else {
                Vue.prototype.$message.error("获取菜单失败！");
                router.push({ path: "/login" });
            }
        });
}


